<template>
  <div class="app-container">
    <!-- 新增的账户详情区域 -->
    <div class="top">账户详情</div>
     <div class="account-info">

      <div class="account-details" >
        <p>
          <span>配送员姓名：</span>{{ riderInfo.name }}
          <span style="margin-left: 40px">手机号码：</span>{{ riderInfo.phone }}
        </p>
        <p>
          <span>工作类型：</span>{{ riderInfo.workType }}
          <span style="margin-left: 40px">账户状态：</span>{{ riderInfo.accountStatus }}
        </p>
        <p>
          <span>账户余额：</span>¥{{ riderInfo.accountBalance }}（保证金额度1000P，已足额缴纳）
        </p>
      </div>
    </div>
    <el-tabs v-model="activeName" class="demo-tabs" >
      <el-tab-pane label="收入明细" name="first">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker clearable
                        v-model="queryParams.updateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery1">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery1">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['accountDetail:detail:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate1"-->
<!--            v-hasPermi="['accountDetail:detail:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['accountDetail:detail:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="Download"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['accountDetail:detail:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getIncomeList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="incomeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="收支类型" align="center" prop="incomeExpenseType" />
      <el-table-column label="账户类型" align="center" prop="accountType" />
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="对账时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="余额" align="center" prop="accountBalance" />
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getIncomeList"
    />

    <!-- 添加或修改账户明细（收入/支出）对话框 -->

      </el-tab-pane>

      <el-tab-pane label="支出明细" name="second"><el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker clearable
                          v-model="queryParams.updateTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery2">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery2">重置</el-button>
        </el-form-item>
      </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['accountDetail:detail:add']"
            >新增</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--                type="success"-->
<!--                plain-->
<!--                icon="Edit"-->
<!--                :disabled="single"-->
<!--                @click="handleUpdate2"-->
<!--                v-hasPermi="['accountDetail:detail:edit']"-->
<!--            >修改</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete2"
                v-hasPermi="['accountDetail:detail:remove']"
            >删除</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--                type="warning"-->
<!--                plain-->
<!--                icon="Download"-->
<!--                @click="handleExport"-->
<!--                v-hasPermi="['accountDetail:detail:export']"-->
<!--            >导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getExpenseList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="expenseList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="收支类型" align="center" prop="incomeExpenseType" />
          <el-table-column label="账户类型" align="center" prop="accountType" />
          <el-table-column label="金额" align="center" prop="amount" />
          <el-table-column label="状态" align="center" prop="status" />
          <el-table-column label="对账时间" align="center" prop="updateTime">

            <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="余额" align="center" prop="accountBalance" />
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getExpenseList"
        />

        <!-- zai -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
          <el-form ref="detailRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="配送员ID" prop="riderId" v-show="false">
              <el-input v-model="form.riderId" />
            </el-form-item>
            <el-form-item label="金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入金额" />
            </el-form-item>
            <el-form-item label="收入支出" prop="detailType">
              <el-select v-model="form.detailType" placeholder="请选择" @change="updateIncomeTypes">
                <el-option label="收入" value="1"></el-option>
                <el-option label="开支" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收支类型" prop="incomeExpenseType">
              <el-select v-model="form.incomeExpenseType" placeholder="请选择">
                <el-option v-for="item in incomeTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="账户类型" prop="accountType">
              <el-select v-model="form.accountType" placeholder="请选择">
                <el-option label="账户余额" value="账户余额"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option label="已入账" value="已入账"></el-option>
                <el-option label="未入账" value="未入账"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog></el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="Detail">
import {
  delDetail,
  addDetail,
  updateDetail,
  getAccount,
  getIncomeDetail, getExpenseDetail, getOneIncome, getOneExpense
} from "@/api/accountDetail/detail"
import { useRoute } from 'vue-router';
import { ref, reactive, computed, getCurrentInstance } from 'vue';

const activeName = ref('first');

const route = useRoute();
const riderId = computed(() => route.params.riderId);
console.log(riderId)
const { proxy } = getCurrentInstance()
console.log(riderId)
const riderInfo = ref({
  name: '',
  phone: '',
  workType: '',
  accountStatus: '',
  accountBalance: 0
});


const incomeList = ref([])
const expenseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    updateTime: null
  },
  rules: {
  },
  incomeTypes: [
    { label: '配送薪资', value: '配送薪资' },
    { label: '奖励提成', value: '奖励提成' }
  ],
  // 新增：收支类型选项映射
  incomeTypeMap: {
    '1': [
      { label: '配送薪资', value: '配送薪资' },
      { label: '奖励提成', value: '奖励提成' }
    ],
    '2': [
      { label: '提现', value: '提现' }
    ]
  },
})

const { queryParams, form, rules,incomeTypes  } = toRefs(data)

// fetch('/riderAccount/account/' + riderId.value)
//     .then(response => {
//       if (!response.ok) throw new Error('接口错误');
//       return response.json();
//     })
//     .then(data => {
//       riderInfo.value = data; // 直接赋值，模板会自动更新
//     })
//     .catch(error => console.error('请求失败：', error));
function getIncomeList(){
  console.log(riderId.value)
  getIncomeDetail(riderId.value).then(response => {
    incomeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getExpenseList(){
  getExpenseDetail(riderId.value).then(response => {
    console.log(response)
    expenseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}



/** 查询账户明细（收入/支出）列表 */
function getAccountInfo() {
  loading.value = true
  console.log(riderId.value)
  getAccount(riderId.value).then(response => {
    console.log(response)
riderInfo.value=response.data
    console.log(riderInfo.value)
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    riderId: null,
    detailType: null,
    incomeExpenseType: null,
    accountType: null,
    amount: null,
    status: null,
    occurTime: null,
    createTime: null,
    updateTime: null
  }
  incomeTypes.value = data.incomeTypeMap['1'] || [];
  proxy.resetForm("detailRef")
}

/** 搜索按钮操作 */
function handleQuery1() {
  queryParams.value.pageNum = 1
  getIncomeList()
}
function handleQuery2() {
  queryParams.value.pageNum = 1
  getExpenseList()
}

/** 重置按钮操作 */
function resetQuery1() {
  proxy.resetForm("queryRef")
  handleQuery1()
}
function resetQuery2() {
  proxy.resetForm("queryRef")
  handleQuery2()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  console.log(ids.value)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  open.value = true
  title.value = "添加账户明细（收入/支出）"
  form.value.riderId = riderId.value;
}
// 新增：处理收入支出变更的方法
function updateIncomeTypes() {
  if (form.value.detailType) {
    // 现在 incomeTypes 已正确解构，可直接赋值
    incomeTypes.value = data.incomeTypeMap[form.value.detailType] || [];
  }
}
/** 修改按钮操作 */
function handleUpdate1(row) {
  reset()
  const _id = row.id || ids.value
  getOneIncome(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改账户明细（收入/支出）"
  })
}
function handleUpdate2(row) {
  reset()
  const _id = row.id || ids.value
  getOneExpense(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改账户明细（收入/支出）"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["detailRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getIncomeList()
        })
      } else {
        addDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getIncomeList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  console.log(_ids)
  proxy.$modal.confirm('是否确认删除账户明细（收入/支出）编号为"' + _ids + '"的数据项？').then(function () {
    return delDetail(_ids)
  }).then(() => {
    getIncomeList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('accountDetail/detail/export', {
    ...queryParams.value
  }, `detail_${new Date().getTime()}.xlsx`)
}

// 新增的冻结账户方法，实际需结合接口实现冻结逻辑
function handleFreezeAccount() {
  proxy.$modal.confirm('是否确认冻结该账户？').then(() => {
    // 这里可调用冻结账户的接口，假设接口为 freezeAccount ，需自行补充
    // freezeAccount(riderId.value).then(() => {
    //   proxy.$modal.msgSuccess('冻结成功');
    // }).catch(() => {
    //   proxy.$modal.msgError('冻结失败');
    // })
  }).catch(() => {
  })
}

getIncomeList()
getAccountInfo()
getExpenseList()
</script>

<style scoped>
.account-info {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #EBF2FE;
  margin-bottom: 10px;
}

.account-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 10px;
}

.account-details p {
  margin: 5px 0;
}

.account-details span {
  font-weight: bold;
}
</style>